package cn.iocoder.yudao.module.picturebook.service.classmember;


import cn.iocoder.yudao.module.picturebook.dal.dataobject.classcheckin.ClassCheckinDO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.classes.ClassesDO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.workmember.WorkMemberDO;
import cn.iocoder.yudao.module.picturebook.dal.mysql.classcheckin.ClassCheckinMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.classes.ClassesMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.classhomework.ClassHomeworkMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.readingrecord.ReadingRecordMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.workmember.WorkMemberMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.picturebook.controller.admin.classmember.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.classmember.ClassMemberDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.classmember.ClassMemberMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.picturebook.enums.ErrorCodeConstants.*;

/**
 * 班级成员关联 Service 实现类
 *
 * @author 芋道源码
 */
@Slf4j
@Service
@Validated
public class ClassMemberServiceImpl implements ClassMemberService {

    @Resource
    private ClassMemberMapper classMemberMapper;
    @Resource
    private ClassesMapper classesMapper;

    @Resource
    private ClassCheckinMapper classCheckinMapper;
    @Resource
    private ReadingRecordMapper readingRecordMapper;
    @Resource
    private ClassHomeworkMapper classHomeworkMapper;
    @Resource
    private WorkMemberMapper workMemberMapper;

    // ... existing code ...
    @Override
    public Long createClassMember(ClassMemberSaveReqVO createReqVO) {
        // 参数校验
        if (createReqVO == null) {
            return null;
        }

        // 插入
        ClassMemberDO classMember = BeanUtils.toBean(createReqVO, ClassMemberDO.class);
        classMemberMapper.insert(classMember);

        // 添加空值检查
        if (classMember.getId() == null) {
            return null;
        }

        // 返回
        return classMember.getId();
    }

    @Override
    public void updateClassMember(ClassMemberSaveReqVO updateReqVO) {
        // 参数校验
        if (updateReqVO == null) {
            return;
        }
        if (updateReqVO.getId() == null) {
            return;
        }

        // 校验存在
        if (classMemberMapper.selectById(updateReqVO.getId()) == null) {
            return;
        }
        // 更新
        ClassMemberDO updateObj = BeanUtils.toBean(updateReqVO, ClassMemberDO.class);
        classMemberMapper.updateById(updateObj);
    }

    @Override
    public void deleteClassMember(Long id) {
        // 参数校验
        if (id == null) {
            return;
        }

        // 校验存在
        if (classMemberMapper.selectById(id) == null) {
            return;
        }
        // 删除
        classMemberMapper.DeleteById(id);
    }

    @Override
    public void deleteClassMemberListByIds(List<Long> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            return;
        }

        // 删除
        classMemberMapper.deleteByIds(ids);
    }


    private void validateClassMemberExists(Long id) {
        // 参数校验
        if (id == null) {
            return;
        }

        if (classMemberMapper.selectById(id) == null) {
            log.error("[getClassMember][id({}) 不存在]", id);
            // 不抛出异常，仅记录日志
            return;
        }
    }

    @Override
    public ClassMemberDO getClassMember(Long id) {
        // 参数校验
        if (id == null) {
            return null;
        }

        return classMemberMapper.selectById(id);
    }

    @Override
    public PageResult<ClassMemberDO> getClassMemberPage(ClassMemberPageReqVO pageReqVO) {
        // 参数校验
        if (pageReqVO == null) {
            return PageResult.empty();
        }

        return classMemberMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ClassMemberDO> getClassByUser(Integer userId) {
        // 参数校验
        if (userId == null) {
            return Collections.emptyList();
        }

        return classMemberMapper.getClassByUser(userId);
    }

    /**
     * 用户加入班级方法
     *
     * @param classCode  班级代码，用于识别特定的班级
     * @param memberName 成员名称，用于记录加入班级的用户名称
     * @param userId     用户ID，用于识别请求加入班级的用户
     * @return 返回一个布尔值，表示用户是否成功加入班级
     */
    @Override
    public Boolean joinClass(String classCode, String memberName, Long userId) {
        // 参数校验
        if (classCode == null || classCode.trim().isEmpty() || userId == null || userId <= 0) {
            return false;
        }

        try {
            // 根据班级代码查询班级信息
            ClassesDO classesDO = classesMapper.queryClassesByClassCode(classCode);
            if (classesDO == null) {
                return false;
            }

            // 检查用户是否已经加入该班级
            ClassMemberDO classMemberDO = classMemberMapper.queryClassMemberByClassIdAndUserId(classesDO.getId(), userId);
            if (classMemberDO != null) {
                return false;
            }

            // 检查班级状态是否为有效状态
            if (!Objects.equals(classesDO.getStatus(), 1)) {
                return false;
            }

            // 创建班级成员保存请求对象
            ClassMemberSaveReqVO reqVO = new ClassMemberSaveReqVO();
            reqVO.setClassId(classesDO.getId());
            reqVO.setMemberName(memberName);
            reqVO.setRole(1);
            reqVO.setUserId(userId);
            // 调用方法创建班级成员记录
            createClassMember(reqVO);
            //查询班级是否有作业存在有就为成员添加联系表
            //获取今天的日期
            LocalDate now = LocalDate.now();
            List<Long> homeworkIds = classHomeworkMapper.getHomeworkByClassId(classesDO.getId(), now);
            if (homeworkIds != null) {
                //先查询作业班级联系表中是否有数据有就不添加
                for (Long homeworkId : homeworkIds) {
                    if (homeworkId != null) {
                        WorkMemberDO workMemberDO = workMemberMapper.queryWorkMemberByWorkIdAndClassIdAndUserId(homeworkId, classesDO.getId(), userId);
                        if (workMemberDO == null) {
                            WorkMemberDO workMemberDO1 = new WorkMemberDO();
                            workMemberDO1.setClassId(classesDO.getId());
                            workMemberDO1.setMemberId(userId);
                            workMemberDO1.setWorkId(homeworkId);
                            workMemberDO1.setStuat(0);
                            workMemberMapper.insert(workMemberDO1);
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("joinClass error", e);
            // 记录日志但不抛出异常
            return false;
        }
    }


    @Override
    public List<ClassMemberDO> getClassByClassId(Long classId) {
        // 参数校验
        if (classId == null) {
            return Collections.emptyList();
        }

        return classMemberMapper.getClassAllMemberByClassId(classId);
    }

    @Override
    public void updateClassMemberRole(Long teacherId, Long id, int i) {
        // 参数校验
        if (teacherId == null || id == null) {
            return;
        }

        classMemberMapper.updateClassMemberRole(teacherId, id, i);
    }

    /**
     * 根据班级ID获取班级成员数据
     *
     * @param classId 班级ID，用于查询班级成员信息
     * @return 返回一个包含班级成员数据的列表如果班级ID无效或未找到成员，则返回空列表
     * <p>
     * 此方法首先验证班级ID的有效性，然后查询该班级的所有成员接着，对每个成员，
     * 批量查询他们的签到信息和阅读记录最后，将这些信息封装到一个响应VO列表中并返回
     */
    @Override
    public List<ClassMemberDataRespVO> getClassDataByClassId(Long classId) {
        // 参数校验
        if (classId == null || classId <= 0) {
            return Collections.emptyList();
        }

        try {
            // 查询成员
            List<ClassMemberDO> classMemberDOList = classMemberMapper.getClassAllMemberByClassId(classId);
            if (classMemberDOList == null || classMemberDOList.isEmpty()) {
                return Collections.emptyList();
            }

            List<ClassMemberDataRespVO> classMemberDataRespVOList = new ArrayList<>(classMemberDOList.size());

            // 获取今日时间
            LocalDate now = LocalDate.now();

            // 提取所有用户ID
            List<Long> userIds = classMemberDOList.stream()
                    .filter(Objects::nonNull)
                    .map(ClassMemberDO::getUserId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量查询签到信息
            Map<Long, Boolean> checkinMap = new HashMap<>();
            for (Long userId : userIds) {
                if (userId != null) {
                    ClassCheckinDO checkin = classCheckinMapper.getByUserIdAndDate(userId, now);
                    checkinMap.put(userId, checkin != null);
                }
            }

            // 批量查询阅读记录
            Map<Long, ReadingStats> readingStatsMap = new HashMap<>();
            for (Long userId : userIds) {
                if (userId != null) {
                    try {
                        int totalDays = readingRecordMapper.getTotalDays(userId);
                        int totalCount = readingRecordMapper.getTotalCount(userId);
                        readingStatsMap.put(userId, new ReadingStats(totalDays, totalCount));
                    } catch (Exception e) {
                        // 出现异常时设置默认值

                        readingStatsMap.put(userId, new ReadingStats(0, 0));
                    }
                }
            }

            // 构建响应数据
            for (ClassMemberDO classMemberDO : classMemberDOList) {
                if (classMemberDO == null) {
                    continue;
                }

                ClassMemberDataRespVO vo = new ClassMemberDataRespVO();
                vo.setId(classMemberDO.getId());
                vo.setClassId(classMemberDO.getClassId());
                vo.setUserId(classMemberDO.getUserId());
                vo.setMemberName(classMemberDO.getMemberName());
                vo.setRole(classMemberDO.getRole());
                vo.setJoinTime(classMemberDO.getJoinTime());
                vo.setCheckin(checkinMap.getOrDefault(classMemberDO.getUserId(), false));

                ReadingStats stats = readingStatsMap.get(classMemberDO.getUserId());
                if (stats != null) {
                    vo.setReadDays(stats.totalDays);
                    vo.setReadCount(stats.totalCount);
                } else {
                    vo.setReadDays(0);
                    vo.setReadCount(0);
                }

                classMemberDataRespVOList.add(vo);
            }

            return classMemberDataRespVOList;
        } catch (Exception e) {
            // 出现异常时返回空列表
            return Collections.emptyList();
        }
    }


    // 辅助类用于封装阅读统计信息
    private static class ReadingStats {
        int totalDays;
        int totalCount;

        ReadingStats(int totalDays, int totalCount) {
            this.totalDays = totalDays;
            this.totalCount = totalCount;
        }
    }

    @Override
    public String getMemberName(Long teacherId, Long id) {
        // 参数校验
        if (teacherId == null || id == null) {
            return "";
        }

        return classMemberMapper.getMemberName(teacherId, id);
    }

    @Override
    public Boolean quitClass(Long classId, Long userId) {
        // 参数校验
        if (classId == null || userId == null) {
            return false;
        }

        //直接删除自己
        return classMemberMapper.deleteByClassIdAndUserId(classId, userId);
    }
// ... existing code ...

}